using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;


/// 14.02.2009 - indexDG - indexul gridului detaliu
/// 



namespace ERPStudio
{
    public partial class FrmWorkspace : StudioForm
    {

        public event BeforeDelHandlerAfterMessage HandleBeforeDelAfterMessage;
        public event ValidatingAfterEndEditHandler HandlerValidatingAfterEndEdit;

        public FrmWorkspace(ModuleClass mInfo) : base(mInfo)
        {
            InitializeComponent();
            this.OnSizeChanged(new EventArgs());
            numeMacheta = Text;
            if (mInfo != null && mInfo.CurrentTheme == "tribunal")
                return;
            HandleMoveFirst += new EventHandler(Primul);
            HandleMoveLast += new EventHandler(Ultimul);
            HandleMoveNext += new EventHandler(Urmator);
            HandleMovePrev += new EventHandler(Anterior);
            HandleAdd += new EventHandler(Adauga);
            HandleDel += new EventHandler(Sterge);
            HandleSearch += new EventHandler(Cauta);
        }
        /// <summary>
        /// doar pentru designer
        /// </summary>
        protected FrmWorkspace(): base(null)
        {
            InitializeComponent();
        }

        public event BeforeDelGridHandler HandleBeforeDelGrid;

        private UpdateOrderOption _updateOrder;
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public UpdateOrderOption UpdateOrder
        {
            get
            {
                return this._updateOrder;
            }
            set
            {
                this._updateOrder = value;
            }
        }
        //public Boolean BackupDataSetBeforeUpdate = true;
        public Boolean AddOnlyMaster = false;
        public Int16 BSMasterIndex = 0;
        public Int16 BSDetailIndex = 1;
        public Int16 BSDetailSaveIndex = 2;
        public Int16 indexDG = 0;
        /// <summary>
        /// daca este setat pe true se va folosii tranzactia la salvarea in baza de date
        /// </summary>
        public Boolean useTranzaction = true;
        /// <summary>
        /// event pentru AddNew la Bindings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void Adauga(object sender, EventArgs args)
        {
            Trace.Assert(gridRezumat.Count != 0, "Nu s-a setat gridRezumat!!!");
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            try
            {
                if (!AddOnlyMaster)
                {
                    if (gridRezumat != null)
                        if (this.gridRezumat[indexDG].ContainsFocus)
                        {
                            if (BSDetailIndex < listBndSourceMain.Count)
                                Trace.Assert(listBndSourceMain[BSDetailIndex] != null, "listBndSourceMain[BSDetailIndex]!=null");
                            if (BSDetailIndex < listBndSourceMain.Count && listBndSourceMain[BSDetailIndex].AllowNew)
                            {
                                listBndSourceMain[BSDetailIndex].AddNew();
                                /// daca a fost definit handlerul afterAdd se va apela
                                /// 
                                Text = numeMacheta + " - Inregistrare noua";
                                DupaAdauga(0);
                            }
                        }
                        else
                        {
                            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a setat listBndSourceMain");
                            Trace.Assert(listBndSourceMain[BSMasterIndex] != null, "listBndSourceMain[BSMasterIndex]!=null");
                            if (listBndSourceMain[BSMasterIndex].AllowNew)
                            {
                                listBndSourceMain[BSMasterIndex].AddNew();
                                /// daca a fost definit handlerul afterAdd se va apela
                                /// 
                                Text = numeMacheta + " - Inregistrare noua";
                                DupaAdauga(0);
                            }
                        }
                }
                else
                {
                    Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a setat listBndSourceMain");
                    Trace.Assert(listBndSourceMain[BSMasterIndex] != null, "listBndSourceMain[BSMasterIndex]!=null");
                    if (listBndSourceMain[BSMasterIndex].AllowNew)
                    {
                        //DataRowView dr = (listBndSourceMain[BSMasterIndex].Current) as DataRowView;
                        ///daca 
                        
                        listBndSourceMain[BSMasterIndex].AddNew();
                        /// daca a fost definit handlerul afterAdd se va apela
                        /// 
                        Text = numeMacheta + " - Inregistrare noua";
                        DupaAdauga(0);
                    }

                }

            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            
        }
        /// <summary>
        /// Functia apelata la apasarea butonului de salvare
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// 
        public DateTime start = DateTime.MaxValue;
        override public void Salvare(object sender, EventArgs args)
        {
            //start = DateTime.Now;
            NoRecUpdated = 0;
            if (ReadOnly)
            {
                return;
            }

            EroareSalvare = false;
            Trace.Assert(this.listTableAdaptor.Count != 0,"Lista listTableAdaptor nu a fost incarcata cu tabele!!");
            SqlTransaction tranz=null;
            if (!Validate())
            {
                EroareSalvare = true; 
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
            Trace.Assert(listBndSourceMain[BSMasterIndex] != null, "listBndSourceMain[BSMasterIndex]!=null");
            if (BSDetailSaveIndex < listBndSourceMain.Count)
                Trace.Assert(listBndSourceMain[BSDetailSaveIndex] != null, "listBndSourceMain[BSDetailSaveIndex]!=null");
            try
            {
                listBndSourceMain[BSMasterIndex].EndEdit();
                if ((BSDetailIndex<listBndSourceMain.Count) && listBndSourceMain[BSDetailIndex] != null)
                    listBndSourceMain[BSDetailIndex].EndEdit();
                for(int i=BSDetailIndex+1;i<listBndSourceMain.Count;i++)
                    listBndSourceMain[i].EndEdit();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex, 0);
                EroareSalvare = true;
                Cursor.Current = Cursors.Default;
                return;
            }

            ValidatingAfterEndEditHandler tempH = HandlerValidatingAfterEndEdit;
            if (tempH != null)
                if (!tempH(this))
                {
                    EroareSalvare = true;
                    return;
                }

            List<DataRow> allChangedRows = new List<DataRow>();
            List<DataRow> allAddedRows = new List<DataRow>();
            //MyTrace("FrmWorkSpace.Salvare.InainteDeSalvare" + (DateTime.Now - start).ToString());
            if (indexDG>=0 && this.gridRezumat[indexDG].GetType() == typeof(RelationTextBox.DataGridview))
            {
                ((RelationTextBox.DataGridview)this.gridRezumat[indexDG]).EnableEvents = false;
            }
            SqlConnection sqlConn = DeschideConexiune(workConnString);
            
            int cate = 0;
            try
            {
                if(useTranzaction)
                    tranz = sqlConn.BeginTransaction(IsolationLevel.ReadCommitted,"Salvare");
                
                InitAdapter(listTableAdaptor[BSindexMaster], sqlConn, tranz);
                for(int i=BSindexDetail;i<listTableAdaptor.Count;i++)
                    if (listTableAdaptor[i] != null)
                    {
                        InitAdapter(listTableAdaptor[i], sqlConn, tranz);
                    }
                //MyTrace("FrmWorkSpace.Salvare.Init.Adaptor" + (DateTime.Now - start).ToString());
                if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete))
                {
                    cate += this.UpdateUpdatedRows(allChangedRows, allAddedRows);
                    cate += this.UpdateInsertedRows(allAddedRows);
                }
                else
                {
                    cate += this.UpdateInsertedRows(allAddedRows);
                    //MyTrace("FrmWorkSpace.Salvare.UpdateInsertedRows" + (DateTime.Now - start).ToString());
                    cate += this.UpdateUpdatedRows(allChangedRows, allAddedRows);
                    //MyTrace("FrmWorkSpace.Salvare.UpdateUpdatedRows" + (DateTime.Now - start).ToString());
                }
                cate += this.UpdateDeletedRows(allChangedRows);
                //MyTrace("FrmWorkSpace.Salvare.UpdateDeletedRows" + (DateTime.Now - start).ToString());
                if(useTranzaction)
                    tranz.Commit();

                if (indexDG>=0 && this.gridRezumat[indexDG].GetType() == typeof(RelationTextBox.DataGridview))
                {
                    ((RelationTextBox.DataGridview)this.gridRezumat[indexDG]).EnableEvents = true;
                }
                if (_DispalySaveStatus)
                {
                    if (cate != 0)
                    {
                        SetStatus("S-au salvat " + cate.ToString() + " inregistrari la: " + DateTime.Now.ToString());
                    }
                    else
                        SetStatus(String.Empty);
                }
                SetTitle();
                NoRecUpdated = cate;
            }
            catch (Exception ex)
            {
                if(useTranzaction)
                    tranz.Rollback();
                Cursor.Current = Cursors.Default;
                TrateazaExceptie(ex);
            }
            InchideConexiune(sqlConn);
            Cursor.Current = Cursors.Default;
            //MyTrace("FrmWorkSpace.Salvare"+(DateTime.Now - start).ToString());
        }
        
        public void Primul(object sender, EventArgs args)
        {
            if (!SalvareLocal()) return;

            try
            {
                //if (this.listBndSourceMain.Count > 0)
                listBndSourceMain[BSMasterIndex].MoveFirst();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        public void Urmator(object sender, EventArgs args)
        {
            if (!SalvareLocal()) return;
            try
            {
                //if (this.listBndSourceMain.Count > 0)
                listBndSourceMain[BSMasterIndex].MoveNext();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        public void Anterior(object sender, EventArgs args)
        {
            if (!SalvareLocal()) return;
            try
            {
                //if (this.listBndSourceMain.Count > 0)
                listBndSourceMain[BSMasterIndex].MovePrevious();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        public void Ultimul(object sender, EventArgs args)
        {
            //in primul e masterul in al doile e details-ul
            if (!SalvareLocal()) return;
            try
            {
                //if (this.listBndSourceMain.Count > 0)
                listBndSourceMain[BSMasterIndex].MoveLast();
                UpdateBounds();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        
        public void Sterge(object sender, EventArgs args)
        {
            if (ReadOnly)
            {
                MessageBox.Show("Macheta este deschisa doar in consultare!",
                    "Eroare",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            String mesaj = "Sunteti sigur ca doriti eliminarea inregistrarii curente";
            Boolean dinGrid = false;
            indexDG = -1;
            for (int i = 0; i < gridRezumat.Count; i++)
            {
                if (this.gridRezumat[i].ContainsFocus)
                {
                    mesaj += " din tabel";
                    indexDG = (short)i;

                    //22.08.2012
                    //cauta binding source pentru gridul selectat
                    for (int j = listBndSourceMain.Count - 1; j >= 0; j--)
                        if (listBndSourceMain[j] == gridRezumat[i].DataSource)
                        {
                            BSDetailIndex = (short)j;
                            break;
                        }

                    dinGrid = true;
 
                }
            }
            mesaj += "?";

            if (MessageBox.Show(mesaj,  "Verificare",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.No)
                return;

            Boolean dacaStergeTmp = true;
            BeforeDelHandlerAfterMessage tempbTmp = HandleBeforeDelAfterMessage;
            if (tempbTmp != null)
                dacaStergeTmp = tempbTmp(this, null,dinGrid);

            if (!dacaStergeTmp)
                return;
            ///dupa mesajul de intrebare se pierde focusul
            try
            {
                if (gridRezumat != null)
                    if (dinGrid)
                    {
                        ///stergerea prin BindingSource
                        ///
                        Boolean dacaSterge = true;
                        BeforeDelGridHandler tempb = HandleBeforeDelGrid;
                        DataGridViewCell dgvc = this.gridRezumat[indexDG].CurrentCell;
                        DataGridViewCellEventArgs param =  null;
                        if(dgvc!=null)
                        {
                            param = new DataGridViewCellEventArgs(dgvc.ColumnIndex,dgvc.RowIndex);
                        }
                        if (tempb != null)
                            dacaSterge = tempb(this.gridRezumat[indexDG], param);
                        if (dacaSterge)
                        {
                            if ((BSDetailIndex >= listBndSourceMain.Count) || listBndSourceMain[BSDetailIndex].Current == null)
                                return;
                            listBndSourceMain[BSDetailIndex].RemoveCurrent();
                        }
                    }
                    else
                    {
                        for (int j = BSDetailIndex; j < listBndSourceMain.Count; j++)
                        {
                            if (listBndSourceMain[j].DataSource == listBndSourceMain[BSMasterIndex])
                            {
                                while (listBndSourceMain[j].Current != null)
                                    listBndSourceMain[j].RemoveCurrent();
                                
                            }
                        }
                        ///este obligatoriu ca delete din relatie sa 
                        ///fie cascade
                        listBndSourceMain[BSMasterIndex].RemoveCurrent();
                        
                    }
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            Update();
            SetTitle();
        }
        override public void Cauta(object sender, EventArgs ev)
        {

            //in primul e masterul in al doile e details-ul
            if (!SalvareLocal()) return;
            try
            {
                Trace.Assert(gridRezumat != null, "nu s-a setat gridul rezumat");
                Trace.Assert(listBndSourceMain[BSMasterIndex] != null, "listBndSourceMain[BSMasterIndex] != null");
                if (gridRezumat != null)
                {
                    FrmSearch frmS= null;
                    SqlConnection conn = DeschideConexiune(workConnString);
                    if (!gridRezumat[indexDG].ContainsFocus)
                    {
                        frmS = new FrmSearch(/*listDataTable[BSindexMaster],*/ listBndSourceMain[BSMasterIndex],conn,ModuleInfo);
                    }
                    else
                    {
                        if (BSDetailIndex < listBndSourceMain.Count)
                        {
                            Trace.Assert(listBndSourceMain[BSDetailIndex] != null, "listBndSourceMain[BSDetailIndex] != null");
                            frmS = new FrmSearch(listBndSourceMain[BSDetailIndex], conn,ModuleInfo);
                        }
                    }
                    frmS.ShowDialog();
                    InchideConexiune(conn);
                }
                UpdateBounds();
                SetTitle();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
            }
            SetTitle();
        }
        
        private void FrmWorkspace_Load(object sender, EventArgs e)
        {
            numeMacheta = Text;
            SetTitle();
            if (ReadOnly)
            {
                foreach (DataGridView dgv in gridRezumat)
                {
                    dgv.AllowUserToAddRows = false;
                    dgv.AllowUserToDeleteRows = false;
                }
                    
            }

        }

        private void FrmWorkspace_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (listBndSourceMain.Count == 0)
                return;
            if (listBndSourceMain.Count > 0)
            {
                currentRow = ((DataRowView)listBndSourceMain[0].Current);
            }
            //daca nu sunt 2 seturi in date verific unul
            //ca sa vedem daca s-a modificat ceva
            //daca apelam EndEdit atuci apare o inregistrare in tabela
            Trace.Assert(listBndSourceMain[BSMasterIndex] != null, "BSMaster neatribuit!!!!!!!!!!11");
            try
            {
                //listBndSourceMain[BSMasterIndex]
                ///dupa apelul lui Endedit inregistrarea curenta prima apare ca si modificata, desi nu s-a modificat
                ///asa ca facem ceva ca sa evitam acest lucru
                ///
                listBndSourceMain[BSMasterIndex].EndEdit();
            }
            catch(Exception)
            {
                // nu ne mai intereseaza exceptiile....
            }
            DataSet _localDS = GetDataTable(BSindexMaster).DataSet;
            e.Cancel = false;
            DataSet dsModificari = _localDS.GetChanges();
            if (dsModificari != null)
            {
                DataTable _localDT = GetDataTable(0);
                //DataSet modificari = _localDT.DataSet.GetChanges();
                DataTable modificari = _localDT.GetChanges();
                Boolean eMod = false;
                String mod = String.Empty;
                if (modificari != null)
                {
                    foreach (DataRow dr in modificari.Rows)
                    {
                        if (dr.RowState == DataRowState.Modified)
                        {
                            if (dr.HasVersion(DataRowVersion.Original))
                            {
                                for (int i = 0; i < modificari.Columns.Count; i++)
                                {
                                    if (dr[i, DataRowVersion.Original].ToString() != dr[i, DataRowVersion.Current].ToString())
                                    {
                                        mod += modificari.Columns[i].ColumnName + ",";
                                        eMod = true;
                                    }
                                }
                            }
                        }
                        else
                            eMod = true;
                    }
                    if (eMod)
                    {
                        if (MessageBox.Show("Renuntati la modificarile efectuate pana acum?(" + mod + ")", "Avertisment",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            e.Cancel = true;
                        }
                    }
                }
            }
        }

        private void dataGridViewMain_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            /*if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
            {
                DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;
                cbo.DropDownStyle = ComboBoxStyle.DropDown;
                cbo.Validating += new CancelEventHandler(cbo_Validating);
            }*/
        }
        void cbo_Validating(object sender, CancelEventArgs e)
        {

            DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;
            DataGridView grid = cbo.EditingControlDataGridView;
            object value = cbo.ValueMember;


            // Add value to list if not there

            if (cbo.Items.IndexOf(value) == -1)
            {
                DataGridViewComboBoxColumn cboCol = grid.Columns[grid.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;

                // Must add to both the current combobox as well as the template, to avoid duplicate entries...

                cbo.Items.Add(value);
                cboCol.Items.Add(value);
                grid.CurrentCell.Value = value;

            }

        }
        /// <summary>
        ///Insert rows in top-down order.
        ///</summary>
        private int UpdateInsertedRows(List<DataRow> allAddedRows)
        {
            int result = 0;

            if ((listTableAdaptor[BSindexMaster] != null))
            {
                DataSet _localDS = listBndSourceMain[BSindexMaster].DataSource as DataSet;
                String _localTableName = listBndSourceMain[BSindexMaster].DataMember;
                DataRow[] addedRows = null;
                if (_localDS != null)
                    addedRows= _localDS.Tables[_localTableName].Select(null, null, DataViewRowState.Added);
                else
                {
                    DataTable _localDT = GetDataTable(BSindexMaster);
                    addedRows = _localDT.Select(null, null, DataViewRowState.Added);
                }
                if (((addedRows != null) && (0 < addedRows.Length)))
                {
                    result = (result + listTableAdaptor[BSindexMaster].Update(addedRows));
                    //MyTrace(listTableAdaptor[BSindexMaster].InsertCommand.CommandText);
                    allAddedRows.AddRange(addedRows);
                }
            }
            for(int i = BSindexDetail;i<listTableAdaptor.Count;i++)
                if (listTableAdaptor[i] != null)
                {
                    DataTable _localDT = GetDataTable(i); 
                    DataRow[] addedRows = _localDT.Select(null, null, DataViewRowState.Added);
                    if (((addedRows != null) && (0 < addedRows.Length)))
                    {
                        result = (result + listTableAdaptor[i].Update(addedRows));
                        //MyTrace(listTableAdaptor[i].InsertCommand.CommandText);
                        allAddedRows.AddRange(addedRows);
                    }
                }
            return result;
        }
        /// <summary>
        ///Delete rows in bottom-up order.
        ///</summary>
        private int UpdateDeletedRows(List<DataRow> allChangedRows)
        {
            int result = 0;
            ///face update la bs-urile detaliu de la coada la cap!
            for (int i = listTableAdaptor.Count - 1; i >= BSindexDetail; i--)
                if (listTableAdaptor[i] != null)
                {
                    DataTable _localDT = GetDataTable(i);
                    DataRow[] deletedRows = _localDT.Select(null, null, DataViewRowState.Deleted);
                    if (((deletedRows != null) && (0 < deletedRows.Length)))
                    {
                        result = (result + listTableAdaptor[i].Update(deletedRows));
                        //MyTrace(listTableAdaptor[i].DeleteCommand.CommandText);
                        allChangedRows.AddRange(deletedRows);
                    }
                }
            if ((listTableAdaptor[BSindexMaster] != null))
            {
                DataSet _localDS = listBndSourceMain[BSindexMaster].DataSource as DataSet;
                String _localTableName = listBndSourceMain[BSindexMaster].DataMember;
                DataRow[] deletedRows = null;
                if (_localDS != null)
                    deletedRows = _localDS.Tables[_localTableName].Select(null, null, DataViewRowState.Deleted);
                else
                {
                    DataTable _localDT = GetDataTable(BSindexMaster);
                    deletedRows = _localDT.Select(null, null, DataViewRowState.Deleted);
                }

                if (((deletedRows != null) && (0 < deletedRows.Length)))
                {
                    result = (result + listTableAdaptor[BSindexMaster].Update(deletedRows));
                    //MyTrace(listTableAdaptor[BSindexMaster].DeleteCommand.CommandText);
                    allChangedRows.AddRange(deletedRows);
                }
            }
            return result;
        }
        /// <summary>
        ///Update rows in top-down order.
        ///</summary>
        private int UpdateUpdatedRows(List<DataRow> allChangedRows, List<DataRow> allAddedRows)
        {
            
            int result = 0;
            if ((listTableAdaptor[BSindexMaster] != null))
            {
                DataSet _localDS = listBndSourceMain[BSindexMaster].DataSource as DataSet;
                String _localTableName = listBndSourceMain[BSindexMaster].DataMember;
                DataRow[] updatedRows = null;
                if (_localDS != null)
                    updatedRows = _localDS.Tables[_localTableName].Select(null, null, DataViewRowState.ModifiedCurrent);
                else
                {
                    DataTable _localDT = GetDataTable(BSindexMaster);
                    updatedRows = _localDT.Select(null, null, DataViewRowState.ModifiedCurrent);
                }
                updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows);
                
                if (((updatedRows != null)
                            && (0 < updatedRows.Length)))
                {
                    start = DateTime.Now;
                    result = (result + listTableAdaptor[BSindexMaster].Update(updatedRows));
                    MyTrace("FrmWorkSpace.Salvare.UpdateUpdatedRows.Master.updatedRows" + (DateTime.Now - start).ToString());
                    allChangedRows.AddRange(updatedRows);
                }
                //MyTrace("FrmWorkSpace.Salvare.UpdateUpdatedRows.Master.AddRange" + (DateTime.Now - start).ToString());
            }
           // MyTrace("FrmWorkSpace.Salvare.UpdateUpdatedRows.Master" + (DateTime.Now - start).ToString());
            for (int i = BSindexDetail; i < listTableAdaptor.Count; i++)
                if (listTableAdaptor[i] != null)
                {
                    DataTable _localDT = GetDataTable(i);
                    DataRow[] updatedRows = _localDT.Select(null, null, DataViewRowState.ModifiedCurrent);
                    updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows);
                    if (((updatedRows != null)
                                && (0 < updatedRows.Length)))
                    {
                        result = (result + listTableAdaptor[i].Update(updatedRows));
                        allChangedRows.AddRange(updatedRows);
                    }
                }
            
            return result;
        }
        /// <summary>
        ///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
        ///</summary>
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        DataRow[] GetRealUpdatedRows(DataRow[] updatedRows, List<DataRow> allAddedRows)
        {
            if (((updatedRows == null) || (updatedRows.Length < 1)))
            {
                return updatedRows;
            }
            if (((allAddedRows == null) || (allAddedRows.Count < 1)))
            {
                return updatedRows;
            }
            List<DataRow> realUpdatedRows = new List<DataRow>();
            for (int i = 0; (i < updatedRows.Length); i = (i + 1))
            {
                DataRow row = updatedRows[i];
                if ((allAddedRows.Contains(row) == false))
                {
                    realUpdatedRows.Add(row);
                }
            }
            return realUpdatedRows.ToArray();
        }
        /// <summary>
        ///Update Order Option
        ///</summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")]
        public enum UpdateOrderOption
        {

            InsertUpdateDelete = 0,

            UpdateInsertDelete = 1,
        }

        public Boolean GetSum(int[] setIndexColoana, DataGridView DGV, out Decimal[] setValSumate)
        {
            setValSumate = new Decimal[setIndexColoana.Length];
            for (int i = 0; i < setValSumate.Length; i++)
                setValSumate[i] = Decimal.Zero;
            if (setIndexColoana.Length == 0)
            {
                MessageBox.Show("Eroare interna:GetSum");
                return false;
            }
            foreach (DataGridViewRow dr in DGV.Rows)
            {
                for (int j = 0; j < setIndexColoana.Length; j++)
                {
                    if (dr.Cells[setIndexColoana[j]].Value != DBNull.Value)
                    {
                        if (dr.Cells[setIndexColoana[j]].IsInEditMode)
                            setValSumate[j] += Convert.ToDecimal(dr.Cells[setIndexColoana[j]].EditedFormattedValue);
                        else
                            setValSumate[j] += Convert.ToDecimal(dr.Cells[setIndexColoana[j]].Value);
                    }
                }
            }
            return true;
        }
    }
}

